<template>
  <basic-container>
    <el-tabs type="border-card" class="chart-tab tab-font" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="产品" name="product"></el-tab-pane>
      <el-tab-pane label="产线" name="productLine"></el-tab-pane>
      <el-tab-pane label="车间" name="workshop"></el-tab-pane>

      <el-row>
        <el-col class="left-area" :span="activeName === 'product' ? 15 : 24">
          <avue-crud
            :option="option"
            :table-loading="loading"
            :data="data"
            :page.sync="page"
            :permission="permissionList"
            :before-open="beforeOpen"
            v-model="form"
            ref="crud"
            @row-update="rowUpdate"
            @row-save="rowSave"
            @row-del="rowDel"
            @row-click="rowClick"
            @search-change="searchChange"
            @search-reset="searchReset"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @refresh-change="refreshChange"
            @on-load="onLoad"
            :key="crudTimer"
            :before-close="beforeClose"
          >
            <template slot="menuLeft">
              <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productPasstRateTargetManage_delete" @click="handleDelete">删 除 </el-button>
              <el-button type="primary" icon="el-icon-plus" size="small" plain @click.stop="handleRulesConfig()">规则配置</el-button>
              <el-button type="primary" icon="el-icon-plus" size="small" plain v-if="activeName === 'workshop'" @click.stop="handlePassConfig()">工厂直通率目标配置</el-button>
            </template>
          </avue-crud>
        </el-col>
        <el-col class="right-area" :span="9" v-if="activeName === 'product'">
          <el-tabs type="border-card" style="margin: 10px" class="el-tabs-right" v-if="isShowDetailTable && activeName === 'product'">
            <el-tab-pane label="工段直通率目标">
              <avue-crud
                :option="detailOption"
                :table-loading="detailLoading"
                :data="detailData"
                :page.sync="detailPage"
                :permission="permissionList"
                ref="detailCrud"
                @row-save="detailRowSave"
                @row-update="detailUpdate"
                @row-del="detailRowDel"
                @selection-change="selectionDetailChange"
                @refresh-change="detailRefreshChange"
                @current-change="currentDetailChange"
                @size-change="sizeDetaillChange"
              >
                <template slot="menuLeft">
                  <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productPasstRateTargetManage_delete && this.rowId" @click="detailHandleDelete"
                    >删 除
                  </el-button>
                  <span v-if="this.rowId" style="margin-left: 10px">名称：{{ this.packingName }}</span>
                </template>
                <template slot-scope="{ row }" slot="isWeight">
                  <el-tag :class="row.isWeight ? 'successTag' : 'dangerTag'">{{ row.isWeight === false ? '否' : '是' }}</el-tag>
                </template>
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-tabs>
    <el-dialog append-to-body :close-on-click-modal="false" title="规则配置" :visible.sync="showRuleDialog" v-if="showRuleDialog" width="30%" top="7vh">
      <h3>不纳入计算范围：</h3>
      <!-- <avue-form ref="properties" v-model="ruleProperties" :option="rulePropertiesOption"></avue-form> -->
      <div class="quantity_contianer">
        <div class="quantityClass">
          <label>产量小于：</label>
          <el-input placeholder="请输入数量" type="number" v-model="ruleProperties.fpyRuleLimit" clearable> </el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="showRuleDialog = false">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleRuleSubmit()" v-preventReClick>保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body :close-on-click-modal="false" title="工厂直通率目标配置" :visible.sync="showPassDialog" v-if="showPassDialog" width="30%" top="7vh">
      <avue-form ref="properties" v-model="passProperties" :option="passPropertiesOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="showPassDialog = false">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handlePassSubmit()" v-preventReClick>保 存</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import { getList, add, remove, getDetail, addRule, getChild, saveDetail, getWorkSectionList, detailRemove, getRuleDetail } from '@/api/report/productPasstRateTargetManage.js';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getTableOption } from '@/views/report/passtRateTargetManage.js';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    var validGoalFpy2 = (rule, value, callback) => {
      if (value != 0 && !value) {
        callback(new Error('请输入目标值'));
      } else {
        if (value <= 0) {
          callback(new Error('目标值要大于0'));
        } else if (value > 100) {
          callback(new Error('目标值要小于100'));
        } else {
          callback();
        }
      }
    };
    return {
      showPassDialog: false,
      showRuleDialog: false,
      crudTimer: new Date().getTime(),
      paramsMap: {
        product: 'PRODUCT',
        workshop: 'WORKSHOP',
        productLine: 'LINE'
      },
      tabMap: {
        workshop: '车间',
        product: '产品',
        productLine: '产线'
      },
      tabMapName: {
        workshop: '车间直通率目标管理',
        product: '产品直通率目标管理',
        productLine: '产线直通率目标管理'
      },
      activeName: 'product',
      form: {},
      query: {},
      loading: true,
      isSubitem: false, //是否新增子项
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      selectionList: [],
      packingQuantity: '',
      ruleProperties: {},
      passProperties: {},
      passPropertiesOption: {
        labelWidth: '130',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '直通率目标值(%)',
            prop: 'fpyGoal',
            type: 'number',
            precision: 0,
            minRows: 1,
            maxRows: 100,
            row: true,
            span: 20,
            rules: [{ required: true, validator: this.validGoalFpy, trigger: 'submit' }]
          },
          {
            label: '',
            prop: 'continueUse',
            type: 'checkbox',
            row: true,
            span: 20,
            // labelWidth: 0,
            dicData: [
              {
                label: '该工厂内所有车间、所有产线都沿用该目标',
                value: 'CHECKBOX'
              }
            ]
          }
        ]
      },
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 8,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        labelWidth: 130,
        menuWidth: 200,
        highlightCurrentRow: true, // 选中高亮
        column: getTableOption('product', this)
      },
      data: [],
      rowId: '',
      selectRow: {},
      packingName: '', //包装配置名称
      tableOption: {}, //公用模态框配置信息
      detailLoading: false,
      dialogTitle: '新增',
      showDialog: false,
      detailData: [], //包装详情数据
      detailOption: {
        //包装详情列表内容配置
        height: 'calc(100vh - 399px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: true,
        delBtn: true,
        cellBtn: true,
        addRowBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 150,
        column: [
          {
            label: '工段',
            prop: 'sectionId',
            width: 150,
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择工段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '目标值',
            prop: 'fpyGoal',
            type: 'number',
            cell: true,
            rules: [{ validator: validGoalFpy2, trigger: 'submit' }]
          }
        ]
      },
      detailForm: {},
      modalName: '', //公用模态框名称
      selectionDetailList: [],
      isShowDetailTable: '',
      workSectionList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.productPasstRateTargetManage_add, false),
        delBtn: this.vaildData(this.permission.productPasstRateTargetManage_delete, false),
        editBtn: this.vaildData(this.permission.productPasstRateTargetManage_edit, false),
        addRowBtn: this.vaildData(this.permission.productPasstRateTargetManage_addRowBtn, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    detailIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit(this.tabMapName[this.activeName]);
      this.isShowDetailTable = true;
    });
  },
  methods: {
    handlePassSubmit() {
      let params = {
        objectType: 'FACTORY',
        fpyGoal: this.passProperties.fpyGoal
      };
      if (this.passProperties && this.passProperties.continueUse.length > 0) {
        params.continueUse = true;
      } else {
        params.continueUse = false;
      }
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          add(params).then(() => {
            this.showPassDialog = false;
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          });
          done();
        }
      });
    },
    handlePassConfig() {
      this.showPassDialog = true;
    },
    handleRuleSubmit() {
      let params = {
        objectType: this.paramsMap[this.activeName],
        fpyRuleLimit: this.ruleProperties.fpyRuleLimit
      };
      addRule(params).then((res) => {
        this.showRuleDialog = false;
        this.ruleProperties = {};
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.onLoad(this.page);
      });
    },
    handleRulesConfig() {
      getRuleDetail({
        objectType: this.paramsMap[this.activeName]
      }).then((res) => {
        let data = res.data.data || {};
        this.$set(this.ruleProperties, 'fpyRuleLimit', data.fpyRuleLimit || '');
      });
      this.showRuleDialog = true;
    },
    newCrudKey() {
      this.crudTimer = new Date().getTime();
    },
    validGoalFpy(rule, value, callback) {
      if (value != 0 && !value) {
        callback(new Error('请输入直通率目标值'));
      } else {
        if (value <= 0) {
          callback(new Error('直通率目标值要大于0'));
        } else if (value > 100) {
          callback(new Error('直通率目标值要小于100'));
        } else {
          callback();
        }
      }
    },
    handleClick() {
      this.query = {};
      this.data = [];
      this.detailData = [];
      const colum = getTableOption(this.activeName, this);
      this.$set(this.option, 'column', colum);
      this.data = [];
      this.newCrudKey();
      this.$nextTick(() => {
        this.$structuralSplit(this.tabMapName[this.activeName]);
        if (this.activeName === 'product') {
          this.isShowDetailTable = true;
        } else {
          this.isShowDetailTable = false;
        }
      });
      this.$refs.crud.refreshTable();
      this.$refs.form.resetForm();
    },
    rowSave(row, done, loading) {
      row.objectType = this.paramsMap[this.activeName];
      if (row.objectType === 'WORKSHOP') {
        if (row.continueUse && row.continueUse.length > 0) {
          row.continueUse = true;
        } else {
          row.continueUse = false;
        }
      }
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.objectType = this.paramsMap[this.activeName];
      if (row.objectType === 'WORKSHOP') {
        if (row.continueUse && row.continueUse.length > 0) {
          row.continueUse = true;
        } else {
          row.continueUse = false;
        }
      }
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.detailData = [];
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          if (this.form.objectType === 'WORKSHOP') {
            if (this.form.continueUse) {
              this.form.continueUse = ['CHECKBOX'];
            } else {
              this.form.continueUse = [];
            }
          }
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      console.log(params, 33333);
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
      this.rowClick(list[len]);
    },
    selectionClear() {
      this.selectionList = [];
      // this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.objectType = this.paramsMap[this.activeName];
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.detailData = [];
        this.selectionDetailClear();
      });
    },
    /**
     * 单击事件
     */
    rowClick(row) {
      if (this.activeName === 'product') {
        this.rowId = row.id;
        this.selectRow = row;
        let column = this.findObject(this.detailOption.column, 'sectionId');
        getWorkSectionList(row.objectId).then(
          (res) => {
            this.workSectionList = this._get(res, 'data.data', []);
            let workSectionList = this._map(this.workSectionList, (item) => {
              return {
                label: item.sectionName,
                value: item.sectionId
              };
            });
            column.dicData = workSectionList;
          },
          (error) => {
            column.dicData = [];
          }
        );
        this.onDetailLoad(this.detailPage);
      }
    },
    /*
     * 打开车间选择模态框
     */
    openWorkshopCommonModal() {
      this.modalName = 'workshopModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择车间信息（双击进行选择）',
        url: '/api/mes-product/workshop/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '车间编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入车间编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '车间名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入车间名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            align: 'center',
            value: 1,
            dataType: 'number',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          }
        ]
      };
    },
    /*
     * 打开产线选择模态框
     */
    openLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: '/api/mes-product/product/line/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true,
            order: 2,
            searchOrder: 2,
            rules: [
              {
                required: true,
                message: '请输入产线名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产线编码',
            prop: 'code',
            maxlength: 20,
            showWordLimit: true,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入产线编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产线状态',
            prop: 'status',
            disabled: true,
            order: 4,
            dataType: 'string',
            type: 'select',
            dicData: [
              {
                label: '待产',
                value: '1'
              },
              {
                label: '生产',
                value: '2'
              },
              {
                label: '停线',
                value: '3'
              }
            ],
            addDisplay: false
          }
        ]
      };
    },
    /**
     * 打开物料选择模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          this.form.objectId = rowData.id;
          this.form.objectCode = rowData.partNo;
          this.form.objectName = rowData.name;
          this.form.partModel = rowData.partModel;
          break;
        case 'lineModal':
          this.form.objectId = rowData.id;
          this.form.objectCode = rowData.code;
          this.form.objectName = rowData.name;
          break;
        case 'workshopModal':
          this.form.objectId = rowData.id;
          this.form.objectCode = rowData.code;
          this.form.objectName = rowData.name;
          break;
        default:
          break;
      }
    },
    onDetailLoad(page, params = {}) {
      this.detailLoading = true;
      getChild(page.currentPage, page.pageSize, {
        parentId: this.selectRow.id,
        objectType: 'SECTION'
      }).then((res) => {
        this.detailLoading = false;
        const data = res.data.data;
        this.detailData = data.records;
        this.detailPage.total = data.total;
        this.detailData.forEach((item) => {
          item.sectionId = item.objectId;
        });
        this.selectionDetailClear();
      });
    },
    detailRefreshChange() {
      this.onDetailLoad(this.detailPage);
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      // this.$refs.detailCrud.toggleSelection();
    },
    detailHandleDelete(scope) {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      console.log(this.selectionDetailList);
      for (let i = 0; i < this.selectionDetailList.length; i++) {
        if (!this.selectionDetailList[i].id) {
          this.$message.warning('未保存的数据无法删除！');
          return;
        }
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return detailRemove(this.detailIds);
        })
        .then(() => {
          this.onDetailLoad(this.detailPage);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.detailCrud.toggleSelection();
        });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    detailRowSave(form, done, loading) {
      let params = {
        parentId: this.selectRow.id,
        fpyGoal: form.fpyGoal,
        objectType: 'SECTION'
      };
      let sectionObj = this._find(this.workSectionList, { sectionId: form.sectionId });
      params['objectId'] = sectionObj.sectionId;
      params['objectName'] = sectionObj.sectionName;
      params['objectCode'] = sectionObj.sectionCode;
      saveDetail(params).then(
        (res) => {
          this.$message.success(res.data.msg);
          this.onDetailLoad(this.detailPage);
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    detailUpdate(form, index, done, loading) {
      let params = {
        id: form.id,
        parentId: this.selectRow.id,
        fpyGoal: form.fpyGoal,
        objectType: 'SECTION'
      };
      let sectionObj = this._find(this.workSectionList, { sectionId: form.sectionId });
      params['objectId'] = sectionObj.sectionId;
      params['objectName'] = sectionObj.sectionName;
      params['objectCode'] = sectionObj.sectionCode;
      saveDetail(params).then(
        (res) => {
          this.$message.success(res.data.msg);
          this.onDetailLoad(this.detailPage);
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    detailRowDel(row, index) {
      if (!row.id) {
        this.detailData.splice(index, 1);
      } else {
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return detailRemove(row.id);
          })
          .then((res) => {
            if (res.data.success) {
              this.onDetailLoad(this.detailPage);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: '操作失败!'
              });
            }
          });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}

.quantity_contianer {
  display: flex;
  justify-content: center;
  .quantityClass {
    display: flex;
    flex-direction: row;
    flex-direction: row;
    align-items: center;
    width: 350px;
    label {
      width: 94px;
    }
  }
}

::v-deep .el-tabs-right .el-tabs__content {
  padding-top: 0;
  padding-bottom: 0;
}

::v-deep .avue-crud__pagination {
  padding: 20px 0 20px 20px;
}
</style>
